import 'dart:async';

import 'package:openvalley_smart_agriculture/models/json/weather_7_days_suggestion_api.dart';
import 'package:openvalley_smart_agriculture/utils/HttpUtil.dart';
import 'package:openvalley_smart_agriculture/utils/StringUtil.dart';
import '../utils/AssetsUtil.dart';

Weather7DaysSuggestionApi? weather7daysSuggestionApi;

class DayWeatherInfo {
  int index = 0;

  //星期几？最近2个是，今天和明天，其他的是星期几
  String? desc;

  //日期
  String? date;

  //天气image地址
  String? weatherImage;

  //风向
  String? windDesc;

  //风速
  String? windSpeed;

  //最低温和最高温
  String? tempMinAndMax;

  //最高温
  String? tempMin;

  //最低温
  String? tempMax;

  //空气质量
  String? aqiDesc;

  //天气类型
  String? type;
}

Future<List<DayWeatherInfo>> getDayWeatherList() async {
  weather7daysSuggestionApi = await apiGetModel<Weather7DaysSuggestionApi>();
  List<DayWeatherInfo> list = [];

  var forecast = weather7daysSuggestionApi?.data?.forecast;
  for (int i = 0; i < 7; i++) {
    var item = forecast?[i];
    DayWeatherInfo dayWeatherInfo = DayWeatherInfo();
    dayWeatherInfo.index = i;
    String? week = "";
    if (i == 0) {
      week = "今天";
    } else if (i == 1) {
      week = "明天";
    } else {
      week = item?.week;
    }
    week = week?.replaceAll("星期", "礼拜");
    week = week?.replaceAll("日", "天");
    week = paddingSpace(week, num: 3);
    dayWeatherInfo.desc = week;
    String date = item?.ymd ?? "2023-01-01";
    String month = date.substring(5, 7);
    String day = date.substring(8);
    dayWeatherInfo.date = "$month/$day";
    String image = getWeatherAsset(item?.type);
    dayWeatherInfo.weatherImage = image;
    dayWeatherInfo.windDesc = item?.fx;
    dayWeatherInfo.windSpeed = item?.fl;
    String lowStr = item?.low ?? "   ";
    String highStr = item?.high ?? "   ";

    String tempMin = lowStr.substring(lowStr.length - 3, lowStr.length).trim();
    String tempMax =
        highStr.substring(highStr.length - 3, highStr.length).trim();

    dayWeatherInfo.tempMinAndMax = "$tempMin-$tempMax";
    dayWeatherInfo.tempMin = tempMin;
    dayWeatherInfo.tempMax = tempMax;

    String aqiDesc = "良";
    int aqi = item?.aqi ?? 50;
    if (0 <= aqi && aqi <= 50) {
      aqiDesc = "优";
    } else if (51 <= aqi && aqi <= 100) {
      aqiDesc = "良";
    } else {
      aqiDesc = "差";
    }
    // else if (101 <= aqi && aqi <= 150) {
    //   aqiDesc = "轻度污染";
    // } else if (151 <= aqi && aqi <= 200) {
    //   aqiDesc = "中度污染";
    // } else if (201 <= aqi && aqi <= 300) {
    //   aqiDesc = "重度污染";
    // } else if (301 <= aqi) {
    //   aqiDesc = "严重污染";
    // }
    // dayWeatherInfo.aqiDesc = paddingSpace(aqiDesc, num: 4, paddingToEnd: false);
    dayWeatherInfo.aqiDesc = aqiDesc;
    dayWeatherInfo.type = item?.type;
    list.add(dayWeatherInfo);
  }
  return list;
}
